package com.bank.common.stringUtil;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {

    //过期时间
    private static long tokenExpiration = 24*60*60*1000;
    //签名秘钥
    private static String tokenSignKey = "123456";

//    根据用户信息创建Token
    public static String createToken(Map<Object,Object> info) {
        String token = Jwts.builder()
                .setSubject("USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("info", info)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    //根据token字符串得到用户信息
    public static Map<Object,Object> getUserInfo(String token) {
        if(StringUtils.isEmpty(token)) return null;

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Map<Object,Object> info = (Map<Object, Object>) claims.get("info");
        return info;
    }


    public static void main(String[] args) {
        Map<Object,Object> info = new HashMap<Object,Object>();
        info.put("userId",4655);
        info.put("userName","lucy");
    }
}

